package com.ltkj.order.service.impl;

import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.ltkj.common.core.constant.CacheConstants;
import com.ltkj.common.core.constant.HttpStatus;
import com.ltkj.common.core.constant.SecurityConstants;
import com.ltkj.common.core.domain.R;
import com.ltkj.common.core.exception.ServiceException;
import com.ltkj.common.core.utils.DateUtils;
import com.ltkj.common.core.utils.HotelCodeUtils;
import com.ltkj.common.core.utils.bean.BeanUtils;
import com.ltkj.common.core.web.domain.AjaxResult;
import com.ltkj.common.datascope.annotation.DataScope;
import com.ltkj.common.rabbitmq.config.RabbitMQConfiguration;
import com.ltkj.common.rabbitmq.server.RabbitmqService;
import com.ltkj.common.redis.RedisLockUtil;
import com.ltkj.common.redis.service.RedisService;
import com.ltkj.common.security.utils.SecurityUtils;
import com.ltkj.coupon.domain.TCouponUser;
import com.ltkj.coupon.mapper.TCouponUserMapper;
import com.ltkj.order.domain.TicOrder;
import com.ltkj.order.domain.TicOrderDetails;
import com.ltkj.order.domain.dto.*;
import com.ltkj.order.domain.vo.*;
import com.ltkj.order.mapper.OrderCouponMapper;
import com.ltkj.order.mapper.TicOrderDetailsMapper;
import com.ltkj.order.mapper.TicOrderMapper;
import com.ltkj.order.service.ITicOrderService;
import com.ltkj.system.api.RemoteGameDataService;
import com.ltkj.system.api.RemoteShopService;
import com.rabbitmq.client.Channel;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 订单Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-09-01
 */
@Service
public class TicOrderServiceImpl implements ITicOrderService 
{

    private static final Logger log = LoggerFactory.getLogger(TicOrderServiceImpl.class);

    @Autowired
    private TicOrderMapper ticOrderMapper;
    @Autowired
    private TicOrderDetailsMapper ticOrderDetailsMapper;
    @Autowired
    private RabbitmqService rabbitmqService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RemoteShopService remoteShopService;
    @Autowired
    private OrderCouponMapper orderCouponMapper;
    @Autowired
    private TCouponUserMapper tCouponUserMapper;
    @Value("${order.delayTime}")
    private Integer delayTime;
    @Autowired
    private RemoteGameDataService remoteGameDataService;

    /**
     * 查询订单
     * 
     * @param orderId 订单主键
     * @return 订单
     */
    @Override
    public TicOrder selectTicOrderByOrderId(Long orderId)
    {
        TicOrder ticOrder = ticOrderMapper.selectTicOrderByOrderId(orderId);
        ticOrder.setWxOrderNum(HotelCodeUtils.buildTicOrderNo());
        ticOrderMapper.updateTicOrder(ticOrder);
        return ticOrder;
    }

    @Override
    public TicOrder orderPayOrderIdDetail(Long orderId) {
        TicOrder ticOrder = ticOrderMapper.selectTicOrderByOrderId(orderId);
        return ticOrder;
    }

    /**
     * 查询订单列表
     * 
     * @param ticOrder 订单
     * @return 订单
     */
    @Override
    public List<TicOrder> selectTicOrderList(TicOrder ticOrder)
    {
        return ticOrderMapper.selectTicOrderList(ticOrder);
    }

    /**
     * 新增订单
     * 
     * @param ticOrder 订单
     * @return 结果
     */
    @Override
    public int insertTicOrder(TicOrder ticOrder)
    {
        ticOrder.setCreateTime(DateUtils.getNowDate());
        return ticOrderMapper.insertTicOrder(ticOrder);
    }

    /**
     * 修改订单
     * 
     * @param ticOrder 订单
     * @return 结果
     */
    @Override
    public int updateTicOrder(TicOrder ticOrder)
    {
        ticOrder.setUpdateTime(DateUtils.getNowDate());
        return ticOrderMapper.updateTicOrder(ticOrder);
    }

    /**
     * 批量删除订单
     * 
     * @param orderIds 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteTicOrderByOrderIds(Long[] orderIds)
    {
        return ticOrderMapper.deleteTicOrderByOrderIds(orderIds);
    }

    /**
     * 删除订单信息
     * 
     * @param orderId 订单主键
     * @return 结果
     */
    @Override
    public int deleteTicOrderByOrderId(Long orderId)
    {
        return ticOrderMapper.deleteTicOrderByOrderId(orderId);
    }
//
//    /**
//     * 新增订单
//     *
//     */
//    @Override
//    public AjaxResult insertOrder(OrderAddDTO addDTO) {
//        TicOrder ticOrder = BeanUtils.copy(addDTO,TicOrder.class);
//        ticOrder.setOrderNum(HotelCodeUtils.buildTicOrderNo());
//        ticOrder.setIsDel("0");
//        ticOrder.setCreateBy(SecurityUtils.getUsername());
//        ticOrder.setCreateTime(new Date());
//        ticOrderMapper.insertTicOrder(ticOrder);
//        addDTO.getTicOrderDetailAddDTOList().stream().filter(x -> x.getOrderNum() == null).map(object->{
//            object.setOrderNum(HotelCodeUtils.buildTicOrderNo());
//            return object;
//        }).collect(Collectors.toList());
//        ticOrderDetailsMapper.insertBatch(addDTO.getTicOrderDetailAddDTOList(),ticOrder.getOrderId(),SecurityUtils.getUsername());
//        return AjaxResult.success();
//    }

    /**
     * 新增订单
     *
     */
    @Override
    public AjaxResult insertOrder(OrderAddDTO addDTO) {
        log.debug("活动抢票入参，{}",new Gson().toJson(addDTO));
        String goodsId = "";
        RLock lock = RedisLockUtil.lock("LOCK");
        try {
            addDTO.getTicOederAddDTO().setUserId(SecurityUtils.getUserId());
            //身份证号和认证方式从redis中取
            UserAuthVo userAuthVo = ticOrderMapper.selectUserAuth(SecurityUtils.getUserId());
            addDTO.getTicOederAddDTO().setOrderTcode(userAuthVo.getUserIdcode());//身份证
            addDTO.getTicOederAddDTO().setOrderTname(userAuthVo.getRealName());//姓名
            addDTO.getTicOederAddDTO().setOrderTphone(userAuthVo.getPhonenumber());//手机号
            addDTO.getTicOederAddDTO().setUserId(SecurityUtils.getUserId());
            String userAuth = "0";
            if ("0".equals(userAuthVo.getPhoneAuth())){
                userAuth = "1";
            }
            if ("0".equals(userAuthVo.getIdcodeAuth())){
                userAuth = "2";
            }
            if ("0".equals(userAuthVo.getFaceAuth())){
                userAuth = "3";
            }
            log.debug("当前用户:{},该用户认证方式：{}",SecurityUtils.getUserId(),userAuth);
            //票的认证方式
            String auth = ticOrderMapper.selectTicketActivityAuth(addDTO.getTicOederAddDTO().getTicketId());
            log.debug("当前购买票需要的认证方式：{}",auth);
            if (auth == null||"".equals(auth)) {
                return AjaxResult.error("该票认证方式异常，无法操作");
            }
            if ("idcard_required".equals(auth)||"phone_required".equals(auth)||"idcard_phone_required".equals(auth)){
                if ("idcard_required".equals(auth)){
                    if (userAuthVo.getUserIdcode()==null||"".equals(userAuthVo.getUserIdcode())){
                        return AjaxResult.error("该票认证方式为身份证必填，请补充");
                    }
                }
                if ("phone_required".equals(auth)){
                    if (userAuthVo.getPhonenumber()==null||"".equals(userAuthVo.getPhonenumber())){
                        return AjaxResult.error("该票认证方式为手机号必填，请补充");
                    }
                }
                if ("idcard_phone_required".equals(auth)){
                    if (userAuthVo.getUserIdcode()==null||"".equals(userAuthVo.getUserIdcode())||userAuthVo.getPhonenumber()==null||"".equals(userAuthVo.getPhonenumber())){
                        return AjaxResult.error("该票认证方式身份证、手机号必填，请补充");
                    }
                }
            }else {
                // 票的认证方式是否与购买人一致
                Integer userAuthS = Integer.parseInt(userAuth);
                Integer authS = Integer.parseInt(auth);
                int compare = Integer.compare(userAuthS, authS);
                log.debug("购买票需要的认证方式比较结果：{}", compare);
                if (compare < 0) {
                    return AjaxResult.error("请完成该票的认证方式后重新购买");
                }
            }
            log.debug("购买开始。。。。。。。。。");
            if ("1".equals(addDTO.getTicOederAddDTO().getOrderTicketType())) {
                //景区
                goodsId = "JQ_"+addDTO.getTicOederAddDTO().getTicketId()+"_"+DateUtils.parseDateToStr("yyyy-MM-dd",addDTO.getTicOederAddDTO().getStcokDate());
            }else if ("3".equals(addDTO.getTicOederAddDTO().getOrderTicketType())) {
                //场馆
                goodsId = "CG_" + addDTO.getTicOederAddDTO().getTicketId()+"_"+DateUtils.parseDateToStr("yyyy-MM-dd",addDTO.getTicOederAddDTO().getStcokDate());
            }else if ("2".equals(addDTO.getTicOederAddDTO().getOrderTicketType())) {
                //活动
                goodsId = "STOCK:HD_" + addDTO.getTicOederAddDTO().getTicketId()+"_"+DateUtils.parseDateToStr("yyyy-MM-dd",addDTO.getTicOederAddDTO().getStcokDate());
            }else if ("4".equals(addDTO.getTicOederAddDTO().getOrderTicketType())) {
                //文创
                goodsId = "WC_" + addDTO.getTicOederAddDTO().getTicketId()+"_"+DateUtils.parseDateToStr("yyyy-MM-dd",addDTO.getTicOederAddDTO().getStcokDate());
            }else {
                return AjaxResult.error("下单异常参数异常请重试");
            }
            if(redisService.hasKey(goodsId+"_"+SecurityUtils.getUserId())){
                return AjaxResult.error("请不要重复下单");
            }

            log.debug("redis库存上锁。。。。。。。。。");
            Object o = new Object();
            o =  redisService.getCacheObject(goodsId);
            Long aLong = Long.valueOf(String.valueOf(o));
            if(aLong>0){
                long stock = redisService.increment(goodsId,-1);
                Gson gson = new Gson();
                addDTO.setGoodsId(goodsId+"_"+addDTO.getTicOederAddDTO().getUserId());
                rabbitmqService.rabbitSend(RabbitMQConfiguration.SECKILL_PRE_ORDER_EXCHANGE_NAME,RabbitMQConfiguration.SECKILL_PRE_ORDER_QUEUE_ROUTING_KEY, gson.toJson(addDTO));
                log.debug("购买资格成功获取。。。。。。。。。");
                //reids中存在购买成功结果
                redisService.setCacheObject(goodsId+"_"+SecurityUtils.getUserId(),null);
                if(stock < 0) {
                    System.out.println("解锁..."+Thread.currentThread().getId());
                    lock.unlock();
                    log.debug("redis库存解锁。。。。。。。。。");
                    return AjaxResult.error("库存异常请重新操作");
                }
                log.debug("剩余库存：" + stock);
            }else {
                log.debug("解锁else..."+Thread.currentThread().getId());
                lock.unlock();
                log.debug("剩余库存else：" + aLong);
                return AjaxResult.error("票已售完");
            }
        } catch (NumberFormatException e) {
            log.error("新增订单异常"+e.getMessage());
            throw new RuntimeException(e);

        }finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
            log.debug("redis库存解锁。。。。。。。。。");
        }
        return AjaxResult.success(goodsId+"_"+SecurityUtils.getUserId());
    }

    // 监听订单支付普通队列-创建订单
    @RabbitListener(queues = RabbitMQConfiguration.SECKILL_PRE_ORDER_QUEUE_NAME)
    public void receiveNormal(Message message, Channel channel) throws Exception {
        this.messageHandle(message, channel);
    }

    private void messageHandle(Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        log.debug("收到消息，开始生成订单。。。。。。。。。");
        try{
            String m = new String(message.getBody());
            log.debug("收到消息,内容为:"+m);
            Gson gson = new Gson();
            OrderAddDTO addDTO = gson.fromJson(m,OrderAddDTO.class);
            TicOrder ticOrder = BeanUtils.copy(addDTO.getTicOederAddDTO(),TicOrder.class);
            BigDecimal totalPrice = new BigDecimal("0.00");
            for (TicOrderDetailAddDTO detailAddDTO:addDTO.getTicOrderDetailAddDTOList()) {
                //查询票单价
                BigDecimal price = ticOrderDetailsMapper.selectTicAcivityPrice(detailAddDTO.getTicConfigId());
                //计算详细订单金额
                detailAddDTO.setTicketMoney(price.multiply(new BigDecimal(detailAddDTO.getTicketCount()+"")).multiply(new BigDecimal("100.00")));

                //计算总订单金额
                totalPrice = totalPrice.add(detailAddDTO.getTicketMoney());
            }
            //是否使用优惠券
            log.debug("使用优惠券，ID为：{}",addDTO.getCouponId());
            if(addDTO.getCouponId()!=null){
                ticOrder.setCouponId(addDTO.getCouponId());
                TCouponUser tCouponUser = tCouponUserMapper.selectTCouponUserById(addDTO.getCouponId());
                //优惠券必须是待使用和在生效期内才可使用
                if ("0".equals(tCouponUser.getStatus())&&tCouponUser.getEffectiveStartTime().compareTo(new Date())<0
                &&new Date().compareTo(tCouponUser.getEffectiveEndTime())<0) {
                    totalPrice = totalPrice.subtract(tCouponUser.getCouponAmount());
                    log.debug("使用优惠券，金额为：{}",tCouponUser.getCouponAmount());
                }
                if (totalPrice.compareTo(new BigDecimal("0"))<=0){
                    totalPrice=new BigDecimal("0");
                }

            }
            //总金额 要加上邮费
            ticOrder.setOrderTotalPrice(totalPrice);
            ticOrder.setOrderNum(HotelCodeUtils.buildTicOrderNo());
            ticOrder.setIsDel("0");
            ticOrder.setOrderStatus("1");
            if (totalPrice.compareTo(new BigDecimal("0.00"))==0) {
                ticOrder.setOrderStatus("2");
                ticOrder.setOrderPayType("2");
            }
            ticOrder.setOrderTime(new Date());
            ticOrder.setCreateBy(SecurityUtils.getUsername());
            ticOrder.setCreateTime(new Date());
            ticOrderMapper.insertTicOrder(ticOrder);
            addDTO.getTicOrderDetailAddDTOList().stream().map(object->{
                object.setOrderNum(HotelCodeUtils.buildTicOrderNo());
                return object;
            }).collect(Collectors.toList());
            if (addDTO.getTicOrderDetailAddDTOList()!=null&&addDTO.getTicOrderDetailAddDTOList().size()>0){
                for (TicOrderDetailAddDTO ticOrderDetailAddDTO:addDTO.getTicOrderDetailAddDTOList()) {
                    TicOrderResuleVo vo = ticOrderMapper.selectTicketActivityByTicketId(ticOrderDetailAddDTO.getTicketId(),ticOrderDetailAddDTO.getTicConfigId());
                    if (vo!=null){
                        ticOrderDetailAddDTO.setTicketName(vo.getTicketName());
                        ticOrderDetailAddDTO.setCommonName(vo.getCommonName());
                        ticOrderDetailAddDTO.setTicketDate(vo.getTicketDate());
                        ticOrderDetailAddDTO.setTicketTypeName(vo.getTicketTypeName());
                        ticOrderDetailAddDTO.setTicketMoney(vo.getTicketMoney());
                    }
                }
            }
            ticOrderDetailsMapper.insertBatch(addDTO.getTicOrderDetailAddDTOList(),ticOrder.getOrderId(),SecurityUtils.getUsername(),ticOrder.getOrderStatus());
            redisService.updateCacheObject(addDTO.getGoodsId(),ticOrder.getOrderId());
            //rabbitmqService.rabbitSend(RabbitMQConfiguration.SECKILL_PRE_ORDER_DELAY_EXCHANGE_NAME,RabbitMQConfiguration.SECKILL_PRE_ORDER_DELAY_QUEUE_ROUTING_KEY,ticOrder.getOrderId()+"'");
            //支付金额为0时 不用延迟队列
            if (totalPrice.compareTo(new BigDecimal("0.00"))!=0) {
                rabbitmqService.publish(RabbitMQConfiguration.DELAY_TASKCHECK_EXCHANGE,RabbitMQConfiguration.DELAY_MAKEUP_ROUTING_KEY,
                        ticOrder.getOrderId()+"",delayTime);
            }
            //更新优惠券状态
            if(addDTO.getCouponId()!=null){
                TCouponUser tCouponUser = tCouponUserMapper.selectTCouponUserById(addDTO.getCouponId());
                //优惠券必须是待使用和在生效期内才可使用
                if ("0".equals(tCouponUser.getStatus())&&tCouponUser.getEffectiveStartTime().compareTo(new Date())<0
                        &&new Date().compareTo(tCouponUser.getEffectiveEndTime())<0) {
                    tCouponUser.setOrderId(ticOrder.getOrderId());
                    tCouponUser.setStatus("1");
                    tCouponUserMapper.updateTCouponUser(tCouponUser);
                }
            }






//            //延迟队列 设置到期时间 10分钟
//            DelayQueue<OrderDelayed> delayQueue = new DelayQueue<>();
//            delayQueue.put(new OrderDelayed(ticOrder.getOrderId(), 600, TimeUnit.SECONDS));
//            // 取队列头部元素是否过期
//            OrderDelayed task = delayQueue.poll();
//            if (task != null) {
//                // 取消订单业务逻辑
//                TicOrder entity = ticOrderMapper.selectTicOrderByOrderId(ticOrder.getOrderId());
//                if (entity != null && "1".equals(entity.getOrderStatus())) {
//                    //订单10分后还未支付
//                    ticOrder.setOrderStatus("3");
//                    ticOrderMapper.updateTicOrder(ticOrder);
//                }
//            }
            log.debug("生成订单结束。。。。。。。。。");
        }catch (Exception e){
            e.printStackTrace();
            log.error("再次将消息退回队列");
           // channel.basicNack(deliveryTag, true, true);
        }
    }
    // 监听延迟死信订单
    // @RabbitListener(queues = RabbitMQConfiguration.SECKILL_PRE_ORDER_DEAD_LETTER_QUEUE_NAME)
    // public void chaoshiQx(Message message, Channel channel) throws Exception {
    //     this.messageHan(message, channel);
    // }

    @RabbitListener(queues = "timedTask", containerFactory = "rabbitListenerContainerFactory")
    @RabbitHandler
    public void process(Message message, Channel channel) throws Exception {
        this.messageHan(message, channel);
    }
    public void messageHan(Message message, Channel channel) throws Exception {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        log.debug("收到消息，异步处理。。。。。。。。。");
        String m = new String(message.getBody());
        log.debug("收到消息,内容为:"+m);
        //查询订单状态
        TicOrder entity = ticOrderMapper.selectTicOrderByOrderId(Long.parseLong(m));
               if (entity != null && "1".equals(entity.getOrderStatus())) {
                   //订单10分后还未支付
                   entity.setOrderStatus("3");
                   ticOrderMapper.updateTicOrder(entity);
                   ticOrderDetailsMapper.updateTicOrderDetailsStatusByOrderId(entity.getOrderId());
                   orderCouponMapper.updateUserCouponByOrderId(entity.getOrderId());
                   //redis中该用户重复购买标识去掉
                   List<OrderDetailsVo> list = ticOrderDetailsMapper.selectTicOrderDetailByOrderId(entity.getOrderId());
                   if (list!=null&&list.size()>0){
                       for (OrderDetailsVo detail:list) {
                           //活动需要退换redis库存即可
                           if ("2".equals(detail.getOrderTicketType())) {
                               String goodsId = "STOCK:HD_" + detail.getTicketId() + "_" + DateUtils.parseDateToStr("yyyy-MM-dd", detail.getTicketDate()) +"_"+ entity.getUserId();
                               log.debug("自动取消后redis清空用户的购买资格,{}",goodsId);
                               redisService.deleteObject(goodsId);
                           }else if("1".equals(detail.getOrderTicketType())){
                               //景区库存回退
                               TicStockDateVo ticStockDateVo = ticOrderDetailsMapper.selectTicStockDate(detail.getTicConfigId());
                               //回退数据库库存
                               ticOrderMapper.updateStockCountByStockDate(ticStockDateVo.getTicketId(), detail.getTicketCount(), ticStockDateVo.getStockDate());
                           }else if("3".equals(detail.getOrderTicketType())){
                               //回退数据库库存
                               Long ticVenuesPeriodId = detail.getTicVenuesPeriodId();
                               log.info("回退数据库库存",detail.toString());
                               ticOrderMapper.updateVenuesPeriodCount(ticVenuesPeriodId,1);
                           }else if("5".equals(detail.getOrderTicketType())){
                               //这里取消订单就删除对应成员的数据。保证赛事成员表里的都是已报名的数据
                               R r = remoteGameDataService.delGameMember(detail.getTicketId(), entity.getUserId(), SecurityConstants.INNER);
                               if(200 == r.getCode()){
                                   log.debug("订单号" + m + "删除赛事报名成员成功!");
                               }else{
                                   log.debug("订单号" + m + "删除赛事报名成员失败!");
                               }

                           }
                       }
                   }
               }
    }

    /**
     * 新增订单
     *
     */
    @Override
    public synchronized AjaxResult addOtherOrder(OrderAddDTO addDTO) {
        Long id = 0L;
        //景区
        if("1".equals(addDTO.getTicOederAddDTO().getOrderTicketType())) {
            UserAuthVo userAuthVo = ticOrderMapper.selectUserAuth(SecurityUtils.getUserId());
            String userAuth = "0";
            if ("0".equals(userAuthVo.getPhoneAuth())){
                userAuth = "1";
            }
            if ("0".equals(userAuthVo.getIdcodeAuth())){
                userAuth = "2";
            }
            if ("0".equals(userAuthVo.getFaceAuth())){
                userAuth = "3";
            }
            //票的认证方式
            String auth = ticOrderMapper.selectTicketAuth(addDTO.getTicOederAddDTO().getTicketId());
            if (auth == null||"".equals(auth)) {
                return AjaxResult.error("该票认证方式异常，无法操作");
            }
            log.debug("该票认证方式为：{}",auth);
            if ("idcard_required".equals(auth)||"phone_required".equals(auth)||"idcard_phone_required".equals(auth)){
                if ("idcard_required".equals(auth)){
                    if (userAuthVo.getUserIdcode()==null||"".equals(userAuthVo.getUserIdcode())){
                        return AjaxResult.error("该票认证方式为身份证必填，请补充");
                    }
                }
                if ("phone_required".equals(auth)){
                    if (userAuthVo.getPhonenumber()==null||"".equals(userAuthVo.getPhonenumber())){
                        return AjaxResult.error("该票认证方式为手机号必填，请补充");
                    }
                }
                if ("idcard_phone_required".equals(auth)){
                    if (userAuthVo.getUserIdcode()==null||"".equals(userAuthVo.getUserIdcode())||userAuthVo.getPhonenumber()==null||"".equals(userAuthVo.getPhonenumber())){
                        return AjaxResult.error("该票认证方式身份证、手机号必填，请补充");
                    }
                }
            }else {
                // 票的认证方式是否与购买人一致
                Integer userAuthS = Integer.parseInt(userAuth);
                Integer authS = Integer.parseInt(auth);
                int compare = Integer.compare(userAuthS, authS);
                log.debug("购买票需要的认证方式比较结果：{}", compare);
                if (compare < 0) {
                    return AjaxResult.error("请完成该票的认证方式后重新购买");
                }
            }
            BigDecimal totalPrice = new BigDecimal("0");
            if (addDTO.getTicOrderDetailAddDTOList() != null && addDTO.getTicOrderDetailAddDTOList().size()>0) {
                for (TicOrderDetailAddDTO ticOrderDetailAddDTO : addDTO.getTicOrderDetailAddDTOList()) {
                    //查询当期库存
                    Integer count = ticOrderMapper.selectStockCount(ticOrderDetailAddDTO.getTicketId(), addDTO.getTicOederAddDTO().getStcokDate());
                    if (count == null || count <=0) {
                        throw new ServiceException("库存异常，无法购买");
                    }
                    TicOrderResuleVo vo = ticOrderMapper.selectTicketSenciByTicketId(ticOrderDetailAddDTO.getTicketId(),ticOrderDetailAddDTO.getTicConfigId());
                    if (vo!=null){
                        ticOrderDetailAddDTO.setTicketName(vo.getTicketName());
                        ticOrderDetailAddDTO.setCommonName(vo.getCommonName());
                        ticOrderDetailAddDTO.setTicketDate(vo.getTicketDate());
                        ticOrderDetailAddDTO.setTicketTypeName(vo.getTicketTypeName());
                        ticOrderDetailAddDTO.setTicketMoney(vo.getTicketMoney());
                    }
                    //查询票单价
                    BigDecimal price = ticOrderDetailsMapper.selectTiSceniccPrice(ticOrderDetailAddDTO.getTicConfigId());
                    price = price.multiply(new BigDecimal(ticOrderDetailAddDTO.getTicketCount()+"")).multiply(new BigDecimal("100.00"));
                    //计算总订单金额
                    totalPrice = totalPrice.add(ticOrderDetailAddDTO.getTicketMoney().add(price));
                }
            }
            //是否使用优惠券
            log.debug("使用优惠券，ID为：{}",addDTO.getCouponId());
            if(addDTO.getCouponId()!=null){
                TCouponUser tCouponUser = tCouponUserMapper.selectTCouponUserById(addDTO.getCouponId());
                log.debug("总金额为：{}",totalPrice);
                log.debug("优惠券状态为：{}",tCouponUser.getStatus());
                log.debug("当前时间为：{}",DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",new Date()));
                log.debug("有效开始时间为：{}",DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",tCouponUser.getEffectiveStartTime()));
                log.debug("有效结束时间为：{}",DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",tCouponUser.getEffectiveEndTime()));
                log.debug("与有效开始时间比较结果为：{}",tCouponUser.getEffectiveStartTime().compareTo(new Date()));
                log.debug("与有效结束时间比较结果为：{}",(new Date()).compareTo(tCouponUser.getEffectiveEndTime()));
                //优惠券必须是待使用和在生效期内才可使用
                if ("0".equals(tCouponUser.getStatus())&&tCouponUser.getEffectiveStartTime().compareTo(new Date())<0
                        &&(new Date()).compareTo(tCouponUser.getEffectiveEndTime())<0) {
                    totalPrice = totalPrice.subtract(tCouponUser.getCouponAmount());
                    log.debug("使用优惠券，金额为：{}",tCouponUser.getCouponAmount());
                }
                if (totalPrice.compareTo(new BigDecimal("0"))<=0){
                    totalPrice=new BigDecimal("0");
                }

            }
            TicOrder ticOrder = BeanUtils.copy(addDTO.getTicOederAddDTO(), TicOrder.class);
            if(addDTO.getCouponId()!=null){
                ticOrder.setCouponId(addDTO.getCouponId());
            }
            ticOrder.setUserId(SecurityUtils.getUserId());
            ticOrder.setOrderTname(userAuthVo.getRealName());//姓名
            ticOrder.setOrderTphone(userAuthVo.getPhonenumber());//手机号
            ticOrder.setOrderTcode(userAuthVo.getUserIdcode());//身份证
            ticOrder.setOrderNum(HotelCodeUtils.buildOtherOrderNo());
            ticOrder.setIsDel("0");
            ticOrder.setOrderStatus("1");
            if (totalPrice.compareTo(new BigDecimal("0.00"))==0) {
                ticOrder.setOrderStatus("2");
                ticOrder.setOrderPayType("2");
            }
            ticOrder.setOrderTime(new Date());
            ticOrder.setCreateBy(SecurityUtils.getUsername());
            ticOrder.setCreateTime(new Date());
            ticOrder.setOrderTotalPrice(totalPrice);
            ticOrderMapper.insertTicOrder(ticOrder);
            addDTO.getTicOrderDetailAddDTOList().stream().filter(x -> x.getOrderNum() == null).map(object -> {
                object.setOrderDetailsNum(HotelCodeUtils.buildOtherOrderNo());
                object.setOrderNum(ticOrder.getOrderNum());
                return object;
            }).collect(Collectors.toList());
            ticOrderDetailsMapper.insertBatch(addDTO.getTicOrderDetailAddDTOList(), ticOrder.getOrderId(), SecurityUtils.getUsername(),ticOrder.getOrderStatus());
            for (TicOrderDetailAddDTO ticOrderDetailAddDTO : addDTO.getTicOrderDetailAddDTOList()) {
                //减少数据库库存
                ticOrderMapper.updateStockCount(ticOrderDetailAddDTO.getTicketId(), ticOrderDetailAddDTO.getTicketCount(), ticOrderDetailAddDTO.getTicketDate());
            }
            //支付金额为0时 不用延迟队列
            if (totalPrice.compareTo(new BigDecimal("0.00"))!=0) {
                //订单超时设置订单状态为取消
                rabbitmqService.publish(RabbitMQConfiguration.DELAY_TASKCHECK_EXCHANGE,RabbitMQConfiguration.DELAY_MAKEUP_ROUTING_KEY,
                        ticOrder.getOrderId()+"",delayTime);
            }
            //更新优惠券状态
            if(addDTO.getCouponId()!=null){
                TCouponUser tCouponUser = tCouponUserMapper.selectTCouponUserById(addDTO.getCouponId());
                //优惠券必须是待使用和在生效期内才可使用
                if ("0".equals(tCouponUser.getStatus())&&tCouponUser.getEffectiveStartTime().compareTo(new Date())<0
                        &&new Date().compareTo(tCouponUser.getEffectiveEndTime())<0) {
                    tCouponUser.setStatus("1");
                    tCouponUser.setOrderId(ticOrder.getOrderId());
                    tCouponUser.setUseTime(new Date());
                    tCouponUser.setUpdateBy(SecurityUtils.getUsername());
                    tCouponUser.setUpdateTime(new Date());
                    tCouponUserMapper.updateTCouponUser(tCouponUser);
                }
            }
            //取值订单ID 后传给前端
            id  = ticOrder.getOrderId();
        }else if("3".equals(addDTO.getTicOederAddDTO().getOrderTicketType())){
        //场馆
            //判断当前票是否存在购买



            UserAuthVo userAuthVo = ticOrderMapper.selectUserAuth(SecurityUtils.getUserId());
            String userAuth = "0";
            if ("0".equals(userAuthVo.getPhoneAuth())){
                userAuth = "1";
            }
            if ("0".equals(userAuthVo.getIdcodeAuth())){
                userAuth = "2";
            }
            if ("0".equals(userAuthVo.getFaceAuth())){
                userAuth = "3";
            }
            //票的认证方式
            String auth = ticOrderMapper.selectVenusTicketAuth(addDTO.getTicOederAddDTO().getTicketId());
            if (auth == null||"".equals(auth)) {
                return AjaxResult.error("该场馆票认证方式异常，无法操作");
            }
            log.debug("该票认证方式为：{}",auth);
            if ("idcard_required".equals(auth)||"phone_required".equals(auth)||"idcard_phone_required".equals(auth)){
                if ("idcard_required".equals(auth)){
                    if (userAuthVo.getUserIdcode()==null||"".equals(userAuthVo.getUserIdcode())){
                        return AjaxResult.error(HttpStatus.ERRORNOTTICKET,"该票认证方式为身份证必填，请补充");
                    }
                }
                if ("phone_required".equals(auth)){
                    if (userAuthVo.getPhonenumber()==null||"".equals(userAuthVo.getPhonenumber())){
                        return AjaxResult.error(HttpStatus.ERRORNOTTICKET,"该票认证方式为手机号必填，请补充");
                    }
                }
                if ("idcard_phone_required".equals(auth)){
                    if (userAuthVo.getUserIdcode()==null||"".equals(userAuthVo.getUserIdcode())||userAuthVo.getPhonenumber()==null||"".equals(userAuthVo.getPhonenumber())){
                        return AjaxResult.error(HttpStatus.ERRORNOTTICKET,"该票认证方式身份证、手机号必填，请补充");
                    }
                }
            }else {
                // 票的认证方式是否与购买人一致
                Integer userAuthS = Integer.parseInt(userAuth);
                Integer authS = Integer.parseInt(auth);
                int compare = Integer.compare(userAuthS, authS);
                log.debug("购买票需要的认证方式比较结果：{}", compare);
                if (compare < 0) {
                    return AjaxResult.error(HttpStatus.ERRORNOTTICKET,"请完成该票的认证方式后重新购买");
                }
            }
            //查询票务信息
            //当前日期已下单不可重复下单
//            if(addDTO.getTicOrderDetailAddDTOList()!=null&&addDTO.getTicOrderDetailAddDTOList().size()>0){
//                if(addDTO.getTicOrderDetailAddDTOList().size()>1){
//                    throw new ServiceException("只能选择一个时间段");
//                }
//            }



            BigDecimal orderPrice= new BigDecimal(new String("0"));

            for(int i=0;i<addDTO.getTicOrderDetailAddDTOList().size();i++){
                TicVenuesPeriodVO ticVenuesPeriodVO = ticOrderMapper.searchTicVenuesPeriodVO(addDTO.getTicOrderDetailAddDTOList().get(i).getPeriodId());
                if(ticVenuesPeriodVO==null){
                    throw new ServiceException("当前时间段不存在");
                }
                if(ticVenuesPeriodVO.getPeriodStockResidue()==0){
                    throw new ServiceException("当前时间段已约满");
                }
                if(ticVenuesPeriodVO.getPeriodStockResidue()-addDTO.getTicOrderDetailAddDTOList().get(i).getTicketCount()<0){
                    throw new ServiceException("当前时间段库存不足");
                }

                if(DateUtils.getCompareToDate(ticVenuesPeriodVO.getVenuesDate())<0){
                    throw new ServiceException("不能预约已过日期");
                }else {
                    //当天时间
                    if(DateUtils.getCompareToDate(ticVenuesPeriodVO.getVenuesDate())==0){
                        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss");
                        LocalTime localTime= LocalTime.parse(ticVenuesPeriodVO.getPeriodTimeEnd().toString(),dtf);
                        boolean after = LocalTime.now().isAfter(localTime);
                        if(after==true){
                            throw new ServiceException("当前时间段已过");
                        }
                    }

                }
                //查询时间戴拿是否下单成功
                TicOrderDetails ticOrderDetails = new TicOrderDetails();
                ticOrderDetails.setTicketId(addDTO.getTicOederAddDTO().getTicketId());
                ticOrderDetails.setOrderTicketType("3");
                ticOrderDetails.setTicVenuesPeriodId(addDTO.getTicOrderDetailAddDTOList().get(i).getPeriodId()+"");
                ticOrderDetails.setTicketStatus("2");
                //当前日期已下单不可重复下单
                //判断


                int orderNum1 = ticOrderMapper.queryorderByTicketId( addDTO.getTicOederAddDTO().getTicketId(), "3",
                        ticVenuesPeriodVO.getVenuesDate(),

                        "2", SecurityUtils.getLoginUser().getUserid());
                if(orderNum1>=1){
                    throw new ServiceException("当前日期已下单不可重复下单!");
                }


                int orderNum = ticOrderMapper.queryorderBy(
                        addDTO.getTicOederAddDTO().getTicketId(), "3", addDTO.getTicOrderDetailAddDTOList().get(i).getPeriodId(),
                        "2", SecurityUtils.getLoginUser().getUserid());
                    if(orderNum>=1){
                        throw new ServiceException("当前时间段已下单不可重复下单!");
                    }



                Integer ticketCount = addDTO.getTicOrderDetailAddDTOList().get(i).getTicketCount();

                orderPrice = orderPrice.add(ticVenuesPeriodVO.getPeriodPrice().multiply(new BigDecimal(ticketCount+"")).multiply(new BigDecimal("100.00")));
                addDTO.getTicOrderDetailAddDTOList().get(i).setTicketMoney(ticVenuesPeriodVO.getPeriodPrice());
                //查询场馆名称
                String commonName = ticOrderMapper.selectOtherBaseByTicOtherBaseId(ticVenuesPeriodVO.getTicOtherBaseId());
                addDTO.getTicOrderDetailAddDTOList().get(i).setCommonName(commonName);
                //查询预约日期
                addDTO.getTicOrderDetailAddDTOList().get(i).setTicketDate(ticVenuesPeriodVO.getVenuesDate());


            }

            //创建订单
            TicOrder ticOrder = BeanUtils.copy(addDTO, TicOrder.class);
            ticOrder.setOrderNum(HotelCodeUtils.buildOtherOrderNo());
            ticOrder.setIsDel("0");
            ticOrder.setCreateBy(SecurityUtils.getUsername());
            ticOrder.setCreateTime(new Date());
            ticOrder.setOrderTime(new Date());
            ticOrder.setOrderTotalPrice(orderPrice);
            ticOrder.setOrderStatus("1");
            ticOrder.setOrderTname(userAuthVo.getRealName());//姓名
            ticOrder.setOrderTphone(userAuthVo.getPhonenumber());//手机号
            ticOrder.setOrderTcode(userAuthVo.getUserIdcode());//身份证
            ticOrder.setUserId(SecurityUtils.getLoginUser().getUserid());
            if (orderPrice.compareTo(new BigDecimal("0.00"))==0) {
                ticOrder.setOrderStatus("2");
                ticOrder.setOrderPayType("2");
            }
            ticOrderMapper.insertTicOrder(ticOrder);

            addDTO.getTicOrderDetailAddDTOList().stream().filter(x -> x.getOrderNum() == null).map(object -> {
                object.setOrderNum(HotelCodeUtils.buildOtherOrderNo());
                return object;
            }).collect(Collectors.toList());
            ticOrderDetailsMapper.insertBatch(addDTO.getTicOrderDetailAddDTOList(), ticOrder.getOrderId(), SecurityUtils.getUsername(),ticOrder.getOrderStatus());
            for (TicOrderDetailAddDTO ticOrderDetailAddDTO : addDTO.getTicOrderDetailAddDTOList()) {
                //减少数据库库存
                ticOrderMapper.updateVenuesPeriodCount(ticOrderDetailAddDTO.getPeriodId(),ticOrderDetailAddDTO.getTicketCount());
            }
            //支付金额为0时 不用延迟队列
            if (orderPrice.compareTo(new BigDecimal("0.00"))!=0) {
                //订单超时设置订单状态为取消
                rabbitmqService.publish(RabbitMQConfiguration.DELAY_TASKCHECK_EXCHANGE,RabbitMQConfiguration.DELAY_MAKEUP_ROUTING_KEY,
                        ticOrder.getOrderId()+"",delayTime);
            }
            //取值订单ID 后传给前端
            id  = ticOrder.getOrderId();
        }else if("4".equals(addDTO.getTicOederAddDTO().getOrderTicketType())){
            //文创
            TicOrder ticOrder = BeanUtils.copy(addDTO.getTicOederAddDTO(), TicOrder.class);
            // 计算总金额
            BigDecimal priceCount = BigDecimal.ZERO;
            for (TicOrderDetailAddDTO ticOrderDetailAddDTO : addDTO.getTicOrderDetailAddDTOList()) {
                BigDecimal price = ticOrderDetailsMapper.selectGoodsPrice(ticOrderDetailAddDTO.getTicketId());
                priceCount = priceCount.add(price.multiply(BigDecimal.valueOf(ticOrderDetailAddDTO.getTicketCount())));
            }
//            BigDecimal priceCount = addDTO.getTicOrderDetailAddDTOList().stream().map(object -> object.getTicketMoney().multiply(BigDecimal.valueOf(object.getTicketCount()))).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
            // 添加运费
            priceCount = priceCount.add(null == ticOrder.getPostagePrice() ? BigDecimal.ZERO : ticOrder.getPostagePrice());
            ticOrder.setOrderNum(HotelCodeUtils.buildOtherOrderNo());
            Date nowDate = DateUtils.getNowDate();
            ticOrder.setOrderTotalPrice(priceCount);
            ticOrder.setIsDel("0");
            ticOrder.setCreateBy(SecurityUtils.getUsername());
            ticOrder.setCreateTime(nowDate);
            ticOrder.setOrderTime(nowDate);
            ticOrder.setOrderStatus("1");
            if (priceCount.compareTo(new BigDecimal("0.00"))==0) {
                ticOrder.setOrderStatus("2");
                ticOrder.setOrderPayType("2");
            }
            ticOrder.setCreateTime(DateUtils.getNowDate());
            ticOrderMapper.insertTicOrder(ticOrder);
            addDTO.getTicOrderDetailAddDTOList().stream().filter(x -> x.getOrderNum() == null).map(object -> {
                object.setOrderNum(HotelCodeUtils.buildOtherOrderNo());
                return object;
            }).collect(Collectors.toList());
            ticOrderDetailsMapper.insertBatch(addDTO.getTicOrderDetailAddDTOList(), ticOrder.getOrderId(), SecurityUtils.getUsername(),ticOrder.getOrderStatus());
            // 从购物车中移除
            if (null != addDTO.getCartIds() && addDTO.getCartIds().length > 0) {
                AjaxResult ajaxResult = remoteShopService.deleteCartByIds(addDTO.getCartIds());
                if (ajaxResult.isError()) {
                    log.error("购物车移除失败！{}", ajaxResult.get(AjaxResult.MSG_TAG));
                }
            }
            //支付金额为0时 不用延迟队列
            if (priceCount.compareTo(new BigDecimal("0.00"))!=0) {
                //订单超时设置订单状态为取消
                rabbitmqService.publish(RabbitMQConfiguration.DELAY_TASKCHECK_EXCHANGE,RabbitMQConfiguration.DELAY_MAKEUP_ROUTING_KEY,
                        ticOrder.getOrderId()+"",delayTime);
            }
            //取值订单ID 后传给前端
            id  = ticOrder.getOrderId();
        }else if("5".equals(addDTO.getTicOederAddDTO().getOrderTicketType())){
            Long gameId = null;
            //赛事报名订单
            TicOrder ticOrder = BeanUtils.copy(addDTO.getTicOederAddDTO(), TicOrder.class);
            // 计算总金额
            BigDecimal priceCount = BigDecimal.ZERO;
            for (TicOrderDetailAddDTO ticOrderDetailAddDTO : addDTO.getTicOrderDetailAddDTOList()) {
                BigDecimal price = ticOrderDetailsMapper.selectGameEntryFee(ticOrderDetailAddDTO.getTicketId());
                //存储转成分
                priceCount = priceCount.add(price.multiply(BigDecimal.valueOf(100.0)));
                gameId = ticOrderDetailAddDTO.getTicketId();
            }
            ticOrder.setOrderNum(HotelCodeUtils.buildOtherOrderNo());
            Date nowDate = DateUtils.getNowDate();
            ticOrder.setOrderTotalPrice(priceCount);
            ticOrder.setIsDel("0");
            ticOrder.setCreateBy(SecurityUtils.getUsername());
            ticOrder.setCreateTime(nowDate);
            ticOrder.setOrderTime(nowDate);
            ticOrder.setOrderStatus("1");
            if (priceCount.compareTo(new BigDecimal("0.00"))==0) {
                ticOrder.setOrderStatus("2");
                ticOrder.setOrderPayType("2");
            }
            ticOrder.setCreateTime(DateUtils.getNowDate());
            ticOrder.setUserId(SecurityUtils.getLoginUser().getUserid());
            ticOrderMapper.insertTicOrder(ticOrder);
            addDTO.getTicOrderDetailAddDTOList().stream().filter(x -> x.getOrderNum() == null).map(object -> {
                object.setOrderNum(HotelCodeUtils.buildOtherOrderNo());
                return object;
            }).collect(Collectors.toList());
            ticOrderDetailsMapper.insertBatch(addDTO.getTicOrderDetailAddDTOList(), ticOrder.getOrderId(), SecurityUtils.getUsername(),ticOrder.getOrderStatus());
            //支付金额为0时 不用延迟队列
            if (priceCount.compareTo(new BigDecimal("0.00"))!=0) {
                //将待支付订单放入缓存，在报名时判断是否存在未支付订单  格式 key:gameId:userId
                redisService.setCacheObject(CacheConstants.GAME_ORDER_NOT_PAY_KEY + gameId + ":" + ticOrder.getUserId(), ticOrder.getOrderId(), delayTime.longValue(), TimeUnit.MILLISECONDS);
                //订单超时设置订单状态为取消
                rabbitmqService.publish(RabbitMQConfiguration.DELAY_TASKCHECK_EXCHANGE,RabbitMQConfiguration.DELAY_MAKEUP_ROUTING_KEY,
                        ticOrder.getOrderId()+"",delayTime);
            }
            //取值订单ID 后传给前端
            id  = ticOrder.getOrderId();
        }else{
            throw new ServiceException("参数异常");
        }
        return AjaxResult.success(id);
    }

    /**
     * 取消订单
     * @param orderIds
     * @return
     */
    @Override
    public AjaxResult cancleOrderByOrderIds(Long[] orderIds) {
        ticOrderMapper.cancleOrderByOrderIds(orderIds);
        ticOrderDetailsMapper.cancleOrderByOrderIds(orderIds);
        //取消订单后优惠券回退会正常状态
        if (orderIds != null&& orderIds.length>0) {
            for (int i = 0; i < orderIds.length; i++) {
                orderCouponMapper.updateUserCouponByOrderId(orderIds[i]);
                //订单10分后还未支付
                TicOrder entity = ticOrderMapper.selectTicOrderByOrderId(orderIds[i]);
                //redis中该用户重复购买标识去掉
                List<OrderDetailsVo> list = ticOrderDetailsMapper.selectTicOrderDetailByOrderId(entity.getOrderId());
                if (list!=null&&list.size()>0){
                    for (OrderDetailsVo detail:list) {
                        //活动需要退换redis库存即可
                        if ("2".equals(detail.getOrderTicketType())) {
                            String goodsId = "STOCK:HD_" + detail.getTicketId() + "_" + DateUtils.parseDateToStr("yyyy-MM-dd", detail.getTicketDate()) +"_"+ entity.getUserId();
                            log.debug("自动取消后redis清空用户的购买资格,{}",goodsId);
                            redisService.deleteObject(goodsId);
                        }else if("1".equals(detail.getOrderTicketType())){
                            //景区库存回退
                            TicStockDateVo ticStockDateVo = ticOrderDetailsMapper.selectTicStockDate(detail.getTicConfigId());
                            //回退数据库库存
                            ticOrderMapper.updateStockCountByStockDate(ticStockDateVo.getTicketId(), detail.getTicketCount(), ticStockDateVo.getStockDate());
                        }else if("3".equals(detail.getOrderTicketType())){
                            //回退数据库库存
                            Long ticVenuesPeriodId = detail.getTicVenuesPeriodId();
                            log.info("回退数据库库存",detail.toString());
                            ticOrderMapper.updateVenuesPeriodCount(ticVenuesPeriodId,1);                          }
                    }
                }
            }
        }

        return AjaxResult.success();
    }

    @Override
    @DataScope(storeAlias = "g")
    public List<TicOrderPageVo> selectTicOrderListNew(TicOrderQueryDTO queryDTO) {
        List<TicOrderPageVo> list = ticOrderMapper.selectTicOrderListNew(queryDTO);
        return list;
    }

    @Override
    @DataScope(storeAlias = "g")
    public List<TicVenuesOrderPageVo> venuesList(TicVenuesOrderQueryDTO queryDTO) {
        List<TicVenuesOrderPageVo> list = ticOrderMapper.venuesList(queryDTO);
        return list;
    }

    @Override
    public List<OrderDetailsVo> selectTicOrderByOrderIdNew(Long orderId) {
        List<OrderDetailsVo> list = ticOrderDetailsMapper.selectTicOrderDetailByOrderId(orderId);
        return list;
    }

    @Override
    public OrderVenuesDetailsVo getVenuesInfo(Long orderId) {
        OrderVenuesDetailsVo orderVenuesDetailsVo = ticOrderMapper.venuesDetails(orderId);
        if(orderVenuesDetailsVo!=null){

            List<OrderVenuesDetailsListVo> orderVenuesDetailsListVos = ticOrderDetailsMapper.selectTicVencesOrderDetailByOrderId(orderId);
            orderVenuesDetailsVo.setDetailsList(orderVenuesDetailsListVos);
        }

        return orderVenuesDetailsVo;
    }

    @Override
    public Long selectOrderResult(String key) {
        Object o = redisService.getCacheObject(key);
        if (o==null){
         throw new ServiceException("订单结果不存在，请重新下单");
        }
        return Long.valueOf(o+"");
    }

    @Override
    public String serverPhone(OrderPhoneQueryDTO queryDTO) {
        String phone = "";
        if ("1".equals(queryDTO.getOrderType())){//景区
            phone = ticOrderDetailsMapper.selectScenicPhone(queryDTO.getOrderId());
        }else if ("2".equals(queryDTO.getOrderType())){//活动
            phone = ticOrderDetailsMapper.selectActivityPhone(queryDTO.getOrderId());
        }else if ("3".equals(queryDTO.getOrderType())){//场馆
            phone = ticOrderDetailsMapper.selectVenuesPhone(queryDTO.getOrderId());
        }else if ("4".equals(queryDTO.getOrderType())){//文创
            phone = ticOrderDetailsMapper.selectShopStorePhone(queryDTO.getOrderId());
        }else {
            throw new ServiceException("订单类型异常");
        }
        return phone;
    }

    @Override
    public TicOrder orderPayDetail(String wxOrdernum) {
        TicOrder ticOrder = ticOrderMapper.orderPayDetail(wxOrdernum);
        return ticOrder;
    }

    @Override
    public AjaxResult orderBack(Long orderId) {
        ticOrderMapper.updateTicOrderStatus(orderId);
        ticOrderDetailsMapper.updateTicOrderDetailsStatus(orderId);
        List<OrderDetailsVo> list = ticOrderDetailsMapper.selectTicOrderDetailByOrderId(orderId);
        if(list!=null&&list.size()>0){
            for (OrderDetailsVo orderDetailsVo: list) {
                if ("1".equals(orderDetailsVo.getOrderTicketType())){
                    //景区库存回退
                   TicStockDateVo ticStockDateVo = ticOrderDetailsMapper.selectTicStockDate(orderDetailsVo.getTicConfigId());
                    //回退数据库库存
                    ticOrderMapper.updateStockCountByStockDate(ticStockDateVo.getTicketId(), orderDetailsVo.getTicketCount(), ticStockDateVo.getStockDate());
                }else if("2".equals(orderDetailsVo.getOrderTicketType())){
                    //活动库存回退
                    TicStockDateVo ticStockDateVo = ticOrderDetailsMapper.selectActStockDate(orderDetailsVo.getTicConfigId());
                    //回退数据库库存
                    String goodsId = "STOCK:HD_" + ticStockDateVo.getTicketId()+"_"+DateUtils.parseDateToStr("yyyy-MM-dd",ticStockDateVo.getStockDate());
                    redisService.increment(goodsId,-1);
                }else if("3".equals(orderDetailsVo.getOrderTicketType())){
                    //回退数据库库存
                    Long ticVenuesPeriodId = orderDetailsVo.getTicVenuesPeriodId();
                    log.info("回退数据库库存",orderDetailsVo.toString());
                    ticOrderMapper.updateVenuesPeriodCount(ticVenuesPeriodId,1);

                }
            }
        }
        //取消订单后优惠券回退会正常状态
        orderCouponMapper.updateUserCouponByOrderId(orderId);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult refundOrderStatus(Long orderId) {
        TicOrder ticOrder = ticOrderMapper.selectTicOrderByOrderId(orderId);
        if(ticOrder!=null){
            ticOrder.setOrderStatus("7");
            ticOrder.setUpdateTime( DateUtils.getNowDate());
            ticOrderMapper.updateTicOrder(ticOrder);
        }
        //取消订单后优惠券回退会正常状态
        orderCouponMapper.updateUserCouponByOrderId(orderId);
        return AjaxResult.success();
    }

    @Override
    public R<List<UserCouponVo>> selectCouponList() {
        UserCouponQueryDTO queryDTO = new UserCouponQueryDTO();
        queryDTO.setUserId(SecurityUtils.getUserId());
        List<UserCouponVo> userCouponVoList = orderCouponMapper.selectCouponList(queryDTO);
        return R.ok(userCouponVoList);
    }

    @Override
    public R<List<UserCouponVo>> selectCouponListByTicket(UserCouponQueryDTO queryDTO) {
        log.debug("参数ruleType：{}",queryDTO.getRuleType());
        log.debug("参数refId：{}",queryDTO.getRefId());
        queryDTO.setUserId(SecurityUtils.getUserId());
        List<UserCouponVo> userCouponVoList =  orderCouponMapper.selectCouponList(queryDTO);
        return R.ok(userCouponVoList);
    }

    @Override
    public AjaxResult backfill(Long orderDetailId, String trackingCode) {
        //回填物流单号
        TicOrderDetails ticOrderDetails = ticOrderDetailsMapper.selectTicOrderDetailsByOrderDetailsId(orderDetailId);
        ticOrderDetails.setTrackingCode(trackingCode);
        ticOrderDetails.setTicketStatus("5");
        ticOrderDetailsMapper.updateTicOrderDetails(ticOrderDetails);
        //订单状态修改为已发货
        TicOrder ticOrder = ticOrderMapper.selectTicOrderByOrderId(ticOrderDetails.getOrderId());
        ticOrder.setOrderStatus("5");
        ticOrderMapper.updateTicOrder(ticOrder);
        return AjaxResult.success();
    }

}
